/**
 * Global Hotkeys Hook
 * 
 * Centralized keyboard shortcuts management
 */

import { useHotkeys } from 'react-hotkeys-hook';
import { useSessionStore } from '@/store/session';
import { useAssistantStore } from '@/store/assistant';

interface UseGlobalHotkeysOptions {
  onToggleSidebar?: () => void;
  onToggleSessionPanel?: () => void;
  onOpenSettings?: () => void;
  onFocusInput?: () => void;
}

export function useGlobalHotkeys(options: UseGlobalHotkeysOptions = {}) {
  const createSession = useSessionStore((state) => state.createSession);
  const selectedAssistant = useAssistantStore((state) => state.selectedAssistant);

  // Ctrl/Cmd + N: New session
  useHotkeys('mod+n', (e) => {
    e.preventDefault();
    createSession(
      selectedAssistant ? `与 ${selectedAssistant.name} 的对话` : '新对话',
      selectedAssistant?.id
    );
  }, [createSession, selectedAssistant]);

  // Ctrl/Cmd + K: Focus input (or open command palette)
  useHotkeys('mod+k', (e) => {
    e.preventDefault();
    if (options.onFocusInput) {
      options.onFocusInput();
    } else {
      // Focus the composer input
      const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
      input?.focus();
    }
  }, [options.onFocusInput]);

  // Ctrl/Cmd + /: Toggle sidebar
  useHotkeys('mod+/', (e) => {
    e.preventDefault();
    options.onToggleSidebar?.();
  }, [options.onToggleSidebar]);

  // Ctrl/Cmd + B: Toggle session panel
  useHotkeys('mod+b', (e) => {
    e.preventDefault();
    options.onToggleSessionPanel?.();
  }, [options.onToggleSessionPanel]);

  // Ctrl/Cmd + ,: Open settings
  useHotkeys('mod+comma', (e) => {
    e.preventDefault();
    options.onOpenSettings?.();
  }, [options.onOpenSettings]);

  // Escape: Close modals/focus composer
  useHotkeys('escape', (e) => {
    // Check if any modal is open
    const hasModal = document.querySelector('[role="dialog"]');
    if (!hasModal) {
      // Focus composer input
      const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
      input?.focus();
    }
  });
}

/**
 * Keyboard shortcuts info
 */
export const HOTKEY_INFO = [
  { keys: ['Ctrl/Cmd', 'N'], description: '新建会话' },
  { keys: ['Ctrl/Cmd', 'K'], description: '聚焦输入框' },
  { keys: ['Ctrl/Cmd', '/'], description: '切换侧边栏' },
  { keys: ['Ctrl/Cmd', 'B'], description: '切换会话面板' },
  { keys: ['Ctrl/Cmd', ','], description: '打开设置' },
  { keys: ['Esc'], description: '关闭弹窗/聚焦输入' },
];
